<?php

namespace App\Containers\AppSection\BankDetail\Tasks;

use App\Containers\AppSection\BankDetail\Data\Repositories\BankDetailRepository;
use App\Containers\AppSection\BankDetail\Models\BankDetail;
use App\Ship\Exceptions\UpdateResourceFailedException;
use App\Ship\Parents\Tasks\Task;

class ChangeMasterAccountTask extends Task
{
    protected BankDetailRepository $repository;

    public function __construct(BankDetailRepository $repository)
    {
        $this->repository = $repository;
    }

    public function run(int $id): BankDetail
    {
        try {
            /** @var BankDetail $bankDetail */
            $bankDetail = $this->repository->find($id);

            /** @var BankDetail $bankDetailMaster */
            $bankDetailMaster = $this->repository->findWhere([
                'master_account' => true,
                'profile_id' => $bankDetail->profile->id
            ])->first();

            $this->repository->update(['master_account' => null], $bankDetailMaster->id);

            return $this->repository->update(['master_account' => true], $id);

        } catch (Exception $exception) {
            throw new UpdateResourceFailedException();
        }
    }
}
